#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <stdio.h>
#include "dll.h"
#include "log.h"

dll_func_t dll = {
	handle:  NULL,
	handle_init:		NULL,
	handle_input:		NULL,
	handle_process:		NULL,
	handle_open:		NULL,
	handle_close:		NULL,
	handle_fini:		NULL,
	handle_timeout:		NULL
};

int register_plugin (const char *file_name)
{
	char *error; 
	int ret_code = -1;

#define DL_REGISTER(h, v, type, name) do { \
	v = (type)dlsym (h, name); \
	if ((error = dlerror ()) != NULL) { \
		printf ("dlsym error, %s\n", error); \
		dlclose (h); \
		h = NULL; \
		goto last; \
	} \
}while (0)

	dll.handle = dlopen (file_name, RTLD_NOW);
	if ((error = dlerror()) != NULL) {
		printf ("dlopen error, %s\n", error);
		goto last;
	}
	
	DL_REGISTER (dll.handle, dll.handle_init, handle_init_t, "handle_init");
	DL_REGISTER (dll.handle, dll.handle_fini, handle_fini_t, "handle_fini");
	DL_REGISTER (dll.handle, dll.handle_open, handle_open_t, "handle_open");
	DL_REGISTER (dll.handle, dll.handle_close, handle_close_t, "handle_close");
	DL_REGISTER (dll.handle, dll.handle_input, handle_input_t, "handle_input");
	DL_REGISTER (dll.handle, dll.handle_process, handle_process_t, "handle_process");
	DL_REGISTER (dll.handle, dll.handle_timeout, handle_timeout_t, "handle_timeout");
	ret_code = 0;
last:
    return ret_code;
}

void unregister_plugin ()
{
	if (dll.handle != NULL){
		dlclose (dll.handle);
		dll.handle = NULL;
	}
}

